/**
 * Created by yanghaijin on 2018/4/25.
 */


let MongoDBUtil = {
    /**
     * mongoclient
     * */
    _mongoClient: null,
    _dbName: "",
    _isConented: false,
    /**
     * 连接MongoDB数据
     * */
    connectMongoDB: function (url, dbName) {
        let self = this;
        if (this._isConented) {
            return;
        }
        if (dbName.length < 1) {
            console.log("数据库名称不能为空！");
            return false;
        }
        this._dbName = dbName;
        this._isConented = true;
        let MongoClient = require("mongodb").MongoClient;
        MongoClient.connect(url, {
            connectTimeoutMS: 30000,
            autoReconnect: true,
            keepAlive: true
        }, function (err, db) {
            if (err) {
                console.log("connect failed");
                self._isConented = false;
                return false;
            } else {
                self._mongoClient = db;
                console.log("conenct success by string of mongodb");
                // MongoDBUtil.close();
                // var st = MongoDBUtil.getTableCount(table, function (count) {
                //     var arr = [];
                //     for (var i = 0; i < 10; i++) {
                //         arr.push(createUser(i + count));
                //     }
                //     MongoDBUtil.insertMany(table, arr);
                // });

                return true;
            }
        });
    },
    /**
     * 关闭数据连接
     * */
    close: function () {
        let self = this;
        if (self._mongoClient) {
            self._mongoClient.logout(function (err, result) {
                if (!err) {
                    console.log("logged out success");
                }
                self._mongoClient.close();
                self._mongoClient = null;
                self._dbName = "";
                console.log("connect close");
            });
        }
    },
    /**
     * 插入一条新数据
     * @param {String} table
     * @param {Object} data
     * @param {Function} callback
     * */
    insertOne: function (table, data, callback) {
        if (this._mongoClient) {
            this._mongoClient.db(this._dbName).collection(table).insertOne(data, function (err, res) {
                if (err) throw err;
                console.log("文档插入成功");
                if (callback) {
                    callback(err, res);
                }
            });
        }
    },

    /**
     * 插入多条数据
     * */
    insertMany: function (table, arr) {
        if (this._mongoClient) {
            this._mongoClient.db(this._dbName).collection(table).insertMany(arr, function (err, res) {
                if (err) throw err;
                console.log("插入的文档数量为: " + res.insertedCount);
            });
        }
    },

    /**
     * 查找指定条件的User
     * @param {String} table
     * @param {Object} condition
     * @return {Array}
     * */
    findUser: function (table, condition) {
        if (this._mongoClient) {
            this._mongoClient.db(this._dbName).collection(table).find(condition).toArray(function (err, result) {
                if (err) throw err;
                return result;
            });
        }
    },

    /**
     * 更新指定表的一条数据
     * @param {String} table 表名
     * @param {Object} condition 查询条件
     * @param {Object} data 更新数据
     * */
    updateOne: function (table, condition, data) {
        if (this._mongoClient) {
            this._mongoClient.db(this._dbName).collection(table).updateOne(condition, {$set: data}, function (err, res) {
                if (err) throw err;
                console.log("文档更新成功");
            });
        }
    },

    /**
     * 删除一条数据
     * */
    deleteOne: function (table, condition) {
        if (this._mongoClient) {
            this._mongoClient.db(this._dbName).collection(table).deleteOne(condition, function (err, obj) {
                if (err) throw err;
                console.log("文档删除成功");
            });
        }
    },

    /**
     * 删除多条数据
     * */
    deleteMany: function (table, condition) {
        if (this._mongoClient) {
            this._mongoClient.db(this._dbName).collection(table).deleteMany(condition, function (err, obj) {
                if (err) throw err;
                console.log(obj.result.n + " 条文档被删除");
            });
        }
    },
    /**
     * 获得指定表数据的条数
     * */
    getTableCount: function (table, func) {
        if (this._mongoClient) {
            this._mongoClient.db(this._dbName).collection(table).count(function (err, count) {
                if (err) throw err;
                func && func(count);
                return count;
            });
        }
    },
    /**
     * 查找并更新
     * @param {String} table
     * @param {Object} filter
     * @param {Object} update
     * @param {Function} callback
     * */
    findOneAndUpdate: function (table, filter, update, callback) {
        if (this._mongoClient) {
            this._mongoClient.db(this._dbName).collection(table).findOneAndUpdate(filter, update, null, function (error, result) {
                if (!result.lastErrorObject.updatedExisting) {
                    console.log("没有查找到该对象");
                }
                callback && callback(result.lastErrorObject.updatedExisting, result.value);
            });
        }
    }
};
module.exports = MongoDBUtil;